package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * daemon thread the collects packets received on a specified port
 * @author jack
 *
 */
public abstract class UDPDaemon extends Thread
{
	private DatagramSocket s;
	
	/**
	 * declares a new udp daemon to listen to the specified port
	 * @param port
	 * @throws SocketException
	 */
	public UDPDaemon(int port) throws SocketException
	{
		setDaemon(true);
		s = new DatagramSocket(port);
		start();
	}
	public void run()
	{
		try
		{
			for(;;)
			{
				DatagramPacket p = new DatagramPacket(new byte[1024], 1024);
				s.receive(p);
				packetReceived(p);
			}
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		System.out.println("UDP daemon terminated");
	}
	protected abstract void packetReceived(DatagramPacket p);
}
